<template>
	<view class="face-capture-container">
		<!-- 顶部标题栏 -->
		<!-- 	<view class="header">
			<view class="title">人脸录入</view>
		</view> -->

		<!-- 摄像头区域 -->
		<view class="camera-container">
			<camera v-if="cameraReady" :device-position="'front'" :flash="'off'" class="camera"
				@initdone="onCameraReady" @error="onCameraError"></camera>

			<!-- 人脸框提示（通过响应式数据控制透明度） -->
			<!-- <view class="face-guide" v-if="cameraReady">
				<view class="face-frame" :style="{ opacity: faceFrameOpacity }"></view>
				<view class="guide-text">{{ guideMessage }}</view>
			</view> -->
		</view>

		<!-- 操作按钮 -->
		<view class="action-buttons">
			<button class="capture-btn" :disabled="!isReady" @click="captureFace">
				{{ isProcessing ? '处理中...' : '拍摄' }}
			</button>
		</view>

		<!-- 结果提示框 -->
		<view class="result-modal" v-if="showResult">
			<view class="result-content">
				<image v-if="resultSuccess" src="/static/success.png" mode="aspectFit"></image>
				<image v-else src="/static/fail.png" mode="aspectFit"></image>
				<view class="result-text">{{ resultMessage }}</view>
				<button class="result-btn" @click="closeResultModal">
					{{ resultSuccess ? '完成' : '重新拍摄' }}
				</button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		onUnmounted
	} from 'vue';
	import {
		ordersApi
	} from '@/package/api/reservationOrders.js';
	import uploadRequest from '../../utils/uploadRequest.js'; // 引入上传工具

	// 状态管理
	const cameraReady = ref(false);
	const isReady = ref(false);
	const isProcessing = ref(false);
	const guideMessage = ref('请将人脸对准框内');
	const showResult = ref(false);
	const resultSuccess = ref(false);
	const resultMessage = ref('');

	// 新增：人脸框透明度响应式数据
	const faceFrameOpacity = ref(1);
	let animationInterval = null;

	// 相机上下文
	let cameraContext = null;
	const bool = ref(false)

	onMounted(() => {
		// 检查相机权限
		wx.getSetting({
			success(res) {
				if (!res.authSetting['scope.camera']) {
					wx.authorize({
						scope: 'scope.camera',
						success() {
							initCamera();
						},
						fail() {
							wx.showModal({
								title: '权限申请',
								content: '需要获取摄像头权限才能进行人脸录入',
								success(res) {
									if (res.confirm) {
										wx.openSetting();
									} else {
										wx.navigateBack();
									}
								}
							});
						}
					});
				} else {
					initCamera();
				}
			}
		});

		// 启动人脸框动画（修改为数据驱动）
		startFaceFrameAnimation();
	});

	onUnmounted(() => {
		// 清理资源
		if (animationInterval) clearInterval(animationInterval);
	});

	// 初始化相机
	const initCamera = () => {
		cameraContext = wx.createCameraContext();
		cameraReady.value = true;
		isReady.value = true;
	};

	// 相机初始化完成
	const onCameraReady = (e) => {
		console.log('相机初始化完成', e);
	};

	// 相机错误处理
	const onCameraError = (e) => {
		console.error('相机错误', e);
		guideMessage.value = '相机初始化失败，请重试';
		isReady.value = false;

		wx.showToast({
			title: '相机错误，请检查权限',
			icon: 'none'
		});
	};

	// 启动人脸框动画（数据驱动）
	const startFaceFrameAnimation = () => {
		let opacity = 1;
		let increasing = false;

		animationInterval = setInterval(() => {
			if (increasing) {
				opacity += 0.1;
				if (opacity >= 1) {
					opacity = 1;
					increasing = false;
				}
			} else {
				opacity -= 0.1;
				if (opacity <= 0.5) {
					opacity = 0.5;
					increasing = true;
				}
			}

			// 更新响应式数据，自动触发视图更新
			faceFrameOpacity.value = opacity;
		}, 100);
	};

	// 拍摄人脸（逻辑不变）
	const captureFace = () => {
		if (!cameraContext || isProcessing.value) return;

		isProcessing.value = true;
		guideMessage.value = '正在处理...';

		cameraContext.takePhoto({
			quality: 'high',
			success: (res) => {
				// 模拟人脸检测过程
				setTimeout(() => {
					const success = Math.random() > 0.3; // 70%概率成功

					if (success) {
						resultSuccess.value = true;
						resultMessage.value = '人脸录入成功';
						bool.value = true;
						uploadFaceImage(res.tempImagePath);
					} else {
						resultSuccess.value = false;
						resultMessage.value = '人脸检测失败，请重新拍摄';
						bool.value = false;
					}

					showResult.value = true;
					isProcessing.value = false;
				}, 1500);
			},
			fail: (err) => {
				console.error('拍摄失败', err);
				guideMessage.value = '拍摄失败，请重试';
				isProcessing.value = false;

				wx.showToast({
					title: '拍摄失败',
					icon: 'none'
				});
			}
		});
	};

	// 上传人脸图片（逻辑不变）
	const uploadFaceImage = async (tempFilePath) => {
		console.log('上传人脸图片:', tempFilePath);

		const result = await uploadRequest({
			filePath: tempFilePath,
			url: '/api/front/hitch/passengerManager/uploadAvatarRenLian',

			header: {
				"Authori-zation": uni.getStorageSync('token'),
			},
			body: {
				"avatar": tempFilePath
			}
		});
		if (result.code == 200 && bool.value == true) {
			console.log(result);
			// 发送请求  
			if (uni.getStorageSync("RenLianBuLu") === "人脸补录") {
				console.log("人脸补录");
				// RenLianBuLuId
				uni.getStorageSync("RenLianBuLuId")

				const res = await ordersApi.updateImageByOrderId(uni.getStorageSync("RenLianBuLuId"), result
					.data)
				uni.setStorageSync("RenLianBuLu", "")
			} else {
				console.log("正常上传");
				const res = await ordersApi.updateImageByOrderDetailId(uni.getStorageSync("orderDetailId"), result
					.data)


				uni.setStorageSync("typeId", -1)
				uni.navigateTo({
					url: "/package/pages/myAppointment/myAppointment"
				})
			}



		}



	};

	// 关闭结果模态框（逻辑不变）
	const closeResultModal = () => {
		showResult.value = false;

		if (resultSuccess.value) {
			wx.navigateBack();
		} else {
			guideMessage.value = '请将人脸对准框内';
		}
	};
</script>

<style scoped>
	/* 样式保持不变，无需修改 */
	.face-capture-container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #000;
	}

	.header {
		padding: 30rpx 20rpx;
		text-align: center;
		background-color: #333;
	}

	.title {
		color: #fff;
		font-size: 36rpx;
		font-weight: bold;
	}

	.camera-container {
		flex: 1;
		position: relative;
		overflow: hidden;
	}

	.camera {
		width: 100%;
		height: 100%;
	}

	.face-guide {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.face-frame {
		width: 600rpx;
		height: 600rpx;
		border: 4rpx solid rgba(255, 255, 255, 0.8);
		border-radius: 50%;
		box-shadow: 0 0 30rpx rgba(255, 255, 255, 0.5);
		position: relative;
	}

	.face-frame::before,
	.face-frame::after {
		content: '';
		position: absolute;
		width: 80rpx;
		height: 80rpx;
		border: 6rpx solid #409eff;
	}

	.face-frame::before {
		top: -10rpx;
		left: -10rpx;
		border-right: none;
		border-bottom: none;
		border-radius: 12rpx 0 0 0;
	}

	.face-frame::after {
		bottom: -10rpx;
		right: -10rpx;
		border-left: none;
		border-top: none;
		border-radius: 0 0 12rpx 0;
	}

	.guide-text {
		margin-top: 40rpx;
		color: #fff;
		font-size: 28rpx;
		background-color: rgba(0, 0, 0, 0.6);
		padding: 10rpx 20rpx;
		border-radius: 10rpx;
	}

	.action-buttons {
		padding: 40rpx 30rpx;
		background-color: #000;
	}

	.capture-btn {
		width: 100%;
		height: 90rpx;
		line-height: 90rpx;
		background-color: #409eff;
		color: #fff;
		font-size: 32rpx;
		border-radius: 45rpx;
		text-align: center;
	}

	.capture-btn[disabled] {
		background-color: #999;
		opacity: 0.7;
	}

	.result-modal {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.7);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 100;
	}

	.result-content {
		background-color: #fff;
		width: 600rpx;
		border-radius: 20rpx;
		padding: 40rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.result-content image {
		width: 120rpx;
		height: 120rpx;
		margin-bottom: 30rpx;
	}

	.result-text {
		font-size: 32rpx;
		color: #333;
		margin-bottom: 40rpx;
		text-align: center;
	}

	.result-btn {
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		background-color: #409eff;
		color: #fff;
		font-size: 30rpx;
		border-radius: 40rpx;
		text-align: center;
	}
</style>